import { defineStore } from "pinia";

interface UserState {
  username: string;
  token: string;
  isLoggedIn: boolean;
  spin: boolean; // 请求的加载动画
  currentPath: string;
  menuValue: string;
  tabList: { id: number; name: string; path: string; closed: boolean }[];
  breadcrumbList: string[];
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    username: '',
    token: '',
    isLoggedIn: false,
    spin: false, // 请求的加载动画
    currentPath: "首页",
    menuValue: "首页",
    tabList: [
      {
        id: 1,
        name: "首页",
        path: "/",
        closed: false
      }
    ],
    breadcrumbList: ["首页"]
  }),
  
  actions: {
    login(payload: { username: string; token: string }) {
      this.username = payload.username;
      this.token = payload.token;
      this.isLoggedIn = true;
      // 保存到 localStorage
      localStorage.setItem('userInfo', JSON.stringify({
        username: this.username,
        token: this.token,
        isLoggedIn: this.isLoggedIn
      }));
    },
    
    logout() {
      this.username = '';
      this.token = '';
      this.isLoggedIn = false;
      localStorage.removeItem('userInfo');
    },
    
    // 初始化状态
    initUserState() {
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        const parsedInfo = JSON.parse(userInfo);
        this.username = parsedInfo.username;
        this.token = parsedInfo.token;
        this.isLoggedIn = parsedInfo.isLoggedIn;
      }
    }
  }
});
